import axios from "axios";


let imageryLayers = [];//影像图层
let tilesLayers = [];//3DTiles图层
//添加天地图图层
function addTDT_ImageryLayer(url) {
    var strToken = "tk=b6673f69c76ae272825e3bf1071f8d3f";
    var strURL = "http://t0.tianditu.gov.cn/img_w/wmts?";
    var strRequest = "?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles";
    var strProvider = strURL + strToken;

    var layer = new Cesium.WebMapTileServiceImageryProvider({
        url: url,//strProvider "http://t0.tianditu.gov.cn/img_w/wmts?tk=b6673f69c76ae272825e3bf1071f8d3f",
        layer: "img",
        style: "default",
        tileMatrixSetID: "w",
        format: "tiles",
        maximumLevel: 18,
    });
    var tdtLayer = viewer.imageryLayers.addImageryProvider(layer);
    var tdtLayer2D = null;
    if (window.viewer2D) {
        tdtLayer2D = window.viewer2D.imageryLayers.addImageryProvider(imageryProvider);
    }
    // imageryLayers.push({ id: url, type: type, layer: tdtLayer });
    return [tdtLayer, tdtLayer2D];
}

//添加高德地图
function addGaoDeMap(url) {
    var imageryProvider = new Cesium.UrlTemplateImageryProvider({
        url: url,//https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}
        layer: "tdtVecBasicLayer",
        style: "default",
        format: "image/png",
        tileMatrixSetID: "GoogleMapsCompatible",
        show: true
    });
    var gaodeLayer = viewer.imageryLayers.addImageryProvider(imageryProvider);
    var gaodeLayer2D = null;
    if (window.viewer2D) {
        gaodeLayer2D = window.viewer2D.imageryLayers.addImageryProvider(imageryProvider);
    }
    // imageryLayers.push({ id: url, type: type, layer: gaodeLayer });
    return [gaodeLayer, gaodeLayer2D];
}

//添加arcgis图层
function AddArcGIS_ImageryLayer(strURL) {
    var imgProvider = new Cesium.ArcGisMapServerImageryProvider({
        url: strURL,
        tilingScheme: new Cesium.WebMercatorTilingScheme()
    });
    var layer = viewer.imageryLayers.addImageryProvider(imgProvider);
    var layer2D = null;
    if (window.viewer2D) {
        layer2D = window.viewer2D.imageryLayers.addImageryProvider(imgProvider)
    }
    // if (color2Alpha != null) {
    //     layer.colorToAlpha = color2Alpha;
    // }
    // imageryLayers.push({ id: strURL, type: type, layer: layer });
    return [layer, layer2D];
}

//加载影像
function handleForDom(data) {
    // let layerData = imageryLayers.filter(item => item.id == data.id);
    // let index = findImageryLayerIndex(data.id);
    let layer = findImageryLayer(data.id);
    if (layer) {
        // let layer = imageryLayers[index].layer;
        // let index = viewer.imageryLayers.indexOf(layer);
        // console.log(index, data.sort);
        // if (data.sort > imageryLayers[index].index) {
        //     viewer.imageryLayers.lower(layer);//下移
        // } else if (data.sort < layerData.index) {
        //     viewer.imageryLayers.raise(layer);//上移
        // }
        // if (data.sort != imageryLayers[index].index) {
        //     imageryLayers[index].index = data.sort;
        // }
        if (data.checked) {
            viewer.imageryLayers.raiseToTop(layer);
        }
        layer.show = data.checked;
        if (window.viewer2D) {
            let layer2D = findImageryLayer(data.id + "2D");
            if (data.checked) {
                window.viewer2D.imageryLayers.raiseToTop(layer2D);
            }
            layer2D.show = data.checked;
        }
    } else {
        if (data.checked) {
            let layer;
            if (data.data.indexOf("arcgis") > -1) {
                layer = AddArcGIS_ImageryLayer(data.data);
            } else {
                layer = addGaoDeMap(data.data);
            }
            imageryLayers.push({ id: data.id, layer: layer[0] });
            if (layer[1]) {
                imageryLayers.push({ id: data.id + "2D", layer: layer[1] });
            }
        }
    }
}
//场景显示移动
function handleForDomScene(data, moveType) {
    let layer = findImageryLayer(data.id);
    if (layer) {
        if (moveType == "Down") {
            viewer.imageryLayers.lower(layer);//下移
            if (window.viewer2D) {
                window.viewer2D.imageryLayers.lower(layer);
            }
        } else if (moveType == "Up") {
            viewer.imageryLayers.raise(layer);//上移
            if (window.viewer2D) {
                window.viewer2D.imageryLayers.raise(layer);
            }
        }
        layer.show = data.checked;
        if (window.viewer2D) {
            let layer2D = findImageryLayer(data.id + "2D");
            if (moveType == "Down") {
                window.viewer2D.imageryLayers.lower(layer2D);//下移
            } else if (moveType == "Up") {
                window.viewer2D.imageryLayers.raise(layer2D);//上移
            }
            layer2D.show = data.checked;
        }
    } else {
        if (data.checked) {
            let layer;
            if (data.data.indexOf("arcgis") > -1) {
                layer = AddArcGIS_ImageryLayer(data.data);
            } else {
                layer = addGaoDeMap(data.data);
            }
            imageryLayers.push({ id: data.id, layer: layer[0] });
            if (layer[1]) {
                imageryLayers.push({ id: data.id + "2D", layer: layer[1] });
            }
        }
    }
}

//根据id查找图层数组的索引
function findImageryLayerIndex(id) {
    var index = -1;
    for (var i = 0; i < imageryLayers.length; i++) {
        if (id == imageryLayers[i].id) {
            index = i;
            break;
        }
    }
    return index;
}

//根据id查找图层
function findImageryLayer(id) {
    var layer = null;
    for (var i = 0; i < imageryLayers.length; i++) {
        if (id == imageryLayers[i].id) {
            layer = imageryLayers[i].layer;
            break;
        }
    }
    return layer;
}

//添加3D瓦片
function add3DTiles(strURL, name) {
    var tileSet = new Cesium.Cesium3DTileset({
        show: true,
        name: name,
        //url: 'http://localhost:9000/model/04b2c670655611ebbcdd612a7854b35d/tileset.json',
        url: strURL,
        backFaceCulling: true,
        skipLevelOfDetail: true,
        baseScreenSpaceError: 256,
        maximumScreenSpaceError: 2, // 数值加大，能让最终成像变模糊
        skipScreenSpaceErrorFactor: 16,
        skipLevels: 1,
        immediatelyLoadDesiredLevelOfDetail: true,
        loadSiblings: false, // 如果为true则不会在已加载完概况房屋后，自动从中心开始超清化房屋
        cullRequestsWhileMoving: true,
        cullRequestsWhileMovingMultiplier: 5, // 值越小能够更快的剔除
        preloadWhenHidden: true,
        preferLeaves: true,
        maximumMemoryUsage: 4096, // 内存分配变小有利于倾斜摄影数据回收，提升性能体验
        progressiveResolutionHeightFraction: 0.2, // 数值偏于0能够让初始加载变得模糊
        dynamicScreenSpaceErrorDensity: 0.5, // 数值加大，能让周边加载变快
        dynamicScreenSpaceErrorFactor: 1, // 不知道起了什么作用没，反正放着吧先
        dynamicScreenSpaceError: false, // 根据测试，有了这个后，会在真正的全屏加载完之后才清晰化房屋
        shadows: Cesium.ShadowMode.DISABLED,
        cullWithChildrenBounds: true,
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000),
        maximumNumberOfLoadedTiles: 300000
        // backFaceCulling: false,
        // maximumScreenSpaceError: 2,
        // shadows: Cesium.ShadowMode.DISABLED,
        // cullWithChildrenBounds: true,
        // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000),
        // maximumNumberOfLoadedTiles: 300000
        //modelMatrix: m
    });
    var tilesetLayer = viewer.scene.primitives.add(tileSet);
    // viewer.zoomTo(tilesetLayer);
    return tilesetLayer;
}
//加载模型
function handleFor3D(data) {
    let layerData = tilesLayers.filter(item => item.id == data.id);
    if (layerData.length > 0) {
        layerData = layerData[0];
        let layer = layerData.layer;
        if (data.checked) {
            viewer.scene.primitives.raiseToTop(layer);
        }
        layer.show = data.checked;
    } else {
        if (data.checked) {
            let layer = add3DTiles(data.data, data.name);
            tilesLayers.push({ id: data.id, layer: layer });
            return layer
        }
    }
}

//添加高程
function SetTerrainLayer(strURL) {
    let terrProvider = new Cesium.CesiumTerrainProvider({
        url: strURL,
        requestVertexNormals: true
    });
    viewer.terrainProvider = terrProvider;
}
//加载高程
function handleForGc(data) {
    if (data.checked) {
        SetTerrainLayer(data.data);
    } else {
        viewer.scene.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
    }
}

//添加图标
function addBillboard(data, type, imageurl) {
    var width = 30, height = 38;
    const image = imageurl || require("../../assets/images/mark1.png");
    viewer.entities.add({
        // id: id,
        type: type,//自定义属性
        name: data.Name,
        show: true,
        position: Cesium.Cartesian3.fromDegrees(data.X, data.Y, 20),
        //orientation: new Cesium.VelocityOrientationProperty(property),
        billboard: {
            image,  //改图片路径
            //eyeOffset: new Cesium.Cartesian3(0, 0, -10),
            width: width,
            height: height,
            scale: 1.0,
            scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 1200, 0.8),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(1.0, 200000.0),
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            show: true
        }
    });
}

//添加线
function addPolyLine(id, name, type, positions, width, color) {
    viewer.entities.add({
        id: id,
        name: name,
        type: type,
        show: true,
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(positions), //[经度，纬度，经度，纬度...]
            // positions: Cesium.Cartesian3.fromDegreesArrayHeights(positions),
            width: width,
            material: Cesium.Color.fromCssColorString(color),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000.0),
            clampToGround: true
            //arcType: Cesium.ArcType.GEODESIC
        },
    });
}

//添加多边形面
function addPolygon(id, type, positions, color) {
    viewer.entities.add({
        id: id,
        type: type,
        show: true,
        polygon: {
            //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            hierarchy: Cesium.Cartesian3.fromDegreesArray(positions),
            material: Cesium.Color.fromCssColorString(color).withAlpha(0.5),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000.0),
        }
    });
}

//添加多边形面带黑色边框线
function addPolygonLine(id, type, positions, color) {
    viewer.entities.add({
        id: id,
        type: type,
        show: true,
        polygon: {
            //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            hierarchy: Cesium.Cartesian3.fromDegreesArray(positions),
            material: Cesium.Color.fromCssColorString(color).withAlpha(0.5),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000.0),
        },
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(positions),
            width: 1,
            material: Cesium.Color.BLACK,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000.0),
            clampToGround: true
        }
    });
}

//添加多边形面带黑色边框线并添加标签
function addPolygonLineLabel(id, type, data, color, alpha) {
    var font = "18px Microsoft YaHei";
    // alpha = alpha | 0.5;
    viewer.entities.add({
        id: id,
        name: data.Name,
        type: type,
        show: true,
        polygon: {
            //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            hierarchy: Cesium.Cartesian3.fromDegreesArray(data.positions),
            material: Cesium.Color.fromCssColorString(color).withAlpha(alpha),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000.0),
        },
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(data.positions),
            width: 1,
            material: Cesium.Color.BLACK,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000.0),
            clampToGround: true
        },
        position: Cesium.Cartesian3.fromDegrees(data.centrepoint.X, data.centrepoint.Y, 10),
        label: {
            text: data.Name,
            font: font,
            fillColor: Cesium.Color.BLACK,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            // horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            // horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000.0),
            show: true
        }
    });
    // viewer.zoomTo(viewer.entities);
    viewer.flyTo(viewer.entities);
}
//解析geojson数据
function geojson(jsonData, dataType) {
    var data = [];
    var length = jsonData.features.length;
    if (dataType == "line") {//线
        for (var i = 0; i < length; i++) {
            var positions = [];
            var arr = jsonData.features[i].geometry.coordinates[0];
            for (var j = 0; j < arr.length; j++) {
                arr[j].splice(2, 1);
                positions = positions.concat(arr[j]);
            }
            data.push({ positions: positions });
        }
    } else if (dataType == "point") {//点
        for (var i = 0; i < length; i++) {
            data.push({
                //Name: "",
                X: jsonData.features[i].geometry.coordinates[0],
                Y: jsonData.features[i].geometry.coordinates[1],
                //Z: jsonData.features[0].geometry.coordinates[2]
            });
        }
    } else if (dataType == "polygon") {//带洞的面(画水面解析代码)
        for (var i = 0; i < length; i++) {
            let name = jsonData.features[i].properties.Name;
            var coordinatesLength =
                jsonData.features[i].geometry.coordinates.length;
            let positions = [];
            for (var k = 0; k < coordinatesLength; k++) {
                positions = [];
                var arrcoordinates = jsonData.features[i].geometry.coordinates[k];
                // if (arrcoordinates.length == 1) {
                //   let arr = arrcoordinates[0];
                //   for (let m = 0; m < arr.length; m++) {
                //     arr[m].splice(2, 1);
                //     positions = positions.concat(arr[m]);
                //   }
                // } else {
                positions = [];
                let holes = [];
                for (var j = 0; j < arrcoordinates.length; j++) {
                    let arr = arrcoordinates[j];
                    holes = [];
                    for (let m = 0; m < arr.length; m++) {
                        arr[m].splice(2, 1);
                        holes = holes.concat(arr[m]);
                    }
                    positions.push(holes);
                }
                // }
                data.push({
                    name: name,
                    positions: positions,
                    point: { X: positions[0][0], Y: positions[0][1] }
                });
            }
        }
    }
    return data;
}

//解析arcgisjson数据
function arcgisjson(jsonData, dataType) {
    var data = [];
    var length = jsonData.features.length;
    if (dataType == "点") {
        for (var i = 0; i < length; i++) {
            data.push({
                Name: jsonData.features[i].attributes.name ? jsonData.features[i].attributes.name : jsonData.features[i].attributes.STNM,
                X: jsonData.features[i].geometry.x,
                Y: jsonData.features[i].geometry.y,
                //Z: json["waterFacility:Z"]
            });
        }
    } else if (dataType == "面") {
        for (var i = 0; i < length; i++) {
            var ringsLength = jsonData.features[i].geometry.rings.length;
            for (var k = 0; k < ringsLength; k++) {
                var positions = [], position = [];
                var X = 0, Y = 0;
                var arr = jsonData.features[i].geometry.rings[k];
                for (var j = 0; j < arr.length; j++) {
                    arr[j].splice(2, 1);
                    positions = positions.concat(arr[j]);
                    X += arr[j][0];
                    Y += arr[j][1];
                }
                position = { X: X / arr.length, Y: Y / arr.length }
                data.push({
                    Name: jsonData.features[i].attributes.name ? jsonData.features[i].attributes.name : jsonData.features[i].attributes.名称,
                    positions: positions,
                    centrepoint: position
                });
            }
        }
    } else if (dataType == "线") {
        for (var i = 0; i < length; i++) {
            var positions = [];
            var arr = jsonData.features[i].geometry.paths[0];
            for (var j = 0; j < arr.length; j++) {
                arr[j].splice(2, 1);
                positions = positions.concat(arr[j]);
            }
            data.push({ positions: positions });
        }
    }
    return data;
}

//根据类型查找Entity
function findEntityByType(type) {
    var entitys = [];
    var entity = viewer.entities.values;
    if (entity.length > 0) {
        entitys = entity.filter(item => item.type === type);
    }
    return entitys;
}

/** 
//jquery ajax获取数据
function ajaxJson(url, functionCall) {
    $.ajax({
        //type: "post",
        //dataType: "json",
        url: url,
        cache: false,
        async: true,
        //contentType: 'application/json',
        success: function (json) {
            if (json != null) {
                json = $.parseJSON(json);
                functionCall(json);
            }
        },
        error: function (data) {
            console.log(data);
        }
    });
}
//根据ajax获取数据
function ajaxWFS(data) {
    try {
        ajaxJson(data.data, function (jsonData) {
            if (jsonData != null) {
                let datas = arcgisjson(jsonData, data.wfsType);
                for (let i = 0; i < datas.length; i++) {
                    if (data.wfsType == "点") {
                        addBillboard(datas[i], data.id);
                    } else if (data.wfsType == "线") {
                        addPolyLine(null, data.name, data.id, datas[i].positions, 2, "yellow");
                    } else if (data.wfsType == "面") {
                        addPolygon(null, data.id, datas[i].positions, "#ffffff");
                    }
                }
            }
        });
    } catch (e) {
        console.log(e);
    }
}*/

//异步根据数据加载点、线、面数据
async function getWFS(data) {
    try {
        let res = await axios.get(data.data, {})
        let resData = res.data;
        if (resData) {
            let datas = arcgisjson(resData, data.wfsType);
            for (let i = 0; i < datas.length; i++) {
                if (data.wfsType == "点") {
                    addBillboard(datas[i], data.id);
                } else if (data.wfsType == "线") {
                    addPolyLine(null, data.name, data.id, datas[i].positions, 2, "yellow");
                } else if (data.wfsType == "面") {
                    addPolygon(null, data.id, datas[i].positions, "#ffffff");
                }
            }
        }
    } catch (e) {
        console.log(e);
    }
}

// //根据数据加载点、线、面数据
// function getWFS(data) {
//     axios.get(data.data).then(response => {
//         let resData = response.data;
//         if (resData) {
//             let datas = arcgisjson(resData, data.wfsType);
//             for (let i = 0; i < datas.length; i++) {
//                 if (data.wfsType == "点") {
//                     addBillboard(datas[i], data.id);
//                 } else if (data.wfsType == "线") {
//                     addPolyLine(null, data.name, data.id, datas[i].positions, 2, "yellow");
//                 } else if (data.wfsType == "面") {
//                     addPolygon(null, data.id, datas[i].positions, "#ffffff");
//                 }
//             }
//         }
//     }).catch(function (error) {
//         // 请求失败处理
//         console.log(error);
//     });
// }

//加载矢量WFS
function handleForWFS(data) {
    let entitys = findEntityByType(data.id);
    if (entitys.length > 0) {
        entitys.filter(item => item.show = data.checked);
    } else {
        if (data.checked) {
            getWFS(data);
        }
    }
}

//删除地图上所有图层、实体
function handleRemoveAll() {
    imageryLayers = [];//影像图层
    tilesLayers = [];//3DTiles图层
    viewer.imageryLayers.removeAll();//删除所有图层
    viewer.scene.primitives.removeAll();//删除所有原始体的集合（3D）
    viewer.scene.terrainProvider = new Cesium.EllipsoidTerrainProvider({});//高程
    viewer.entities.removeAll();//删除所有实体
}




export default {
    handleForDom,
    handleForGc,
    handleFor3D,
    handleForWFS,
    handleForDomScene,
    handleRemoveAll,
}

